package utility

import (
	"context"
	"github.com/gogf/gf/v2/crypto/gdes"
	"github.com/gogf/gf/v2/encoding/gbase64"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
)

type uAuth struct {
}

var Auth = uAuth{}

func (u *uAuth) EncryptData(ctx context.Context, cipherText string) (text string, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		cbc, err := gdes.EncryptCBC(gconv.Bytes(cipherText), g.Config().MustGet(ctx, "auth.key").Bytes(), g.Config().MustGet(ctx, "auth.iv").Bytes(), gdes.PKCS5PADDING)
		if err != nil {
			return
		}
		text = gbase64.EncodeToString(cbc)
	})
	return
}

func (u *uAuth) DecryptData(ctx context.Context, cipherText string) (text string, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		cbc, err := gdes.DecryptCBC(gconv.Bytes(gbase64.MustDecodeString(cipherText)), g.Config().MustGet(ctx, "auth.key").Bytes(), g.Config().MustGet(ctx, "auth.iv").Bytes(), gdes.PKCS5PADDING)
		if err != nil {
			return
		}
		text = gconv.String(cbc)
	})
	return
}
